package cn.commander.baseEntity;

import cn.commander.utils.CustomDateSerializer;
import cn.commander.utils.DateUtils;
import cn.commander.utils.IdGen;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.InvalidSessionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.util.Date;


public abstract class DataEntity<T> extends BaseEntity<T> {

	private static final Logger LOGGER = LoggerFactory.getLogger(DataEntity.class);

	private static final long serialVersionUID = 1L;

	private String createBy;
	private String updateBy;

	@JsonSerialize(using = CustomDateSerializer.class)
	protected Date createTime; // 创建时间
	@JsonSerialize(using = CustomDateSerializer.class)
	protected Date updateTime; // 更新时间
	protected String remark; // 备注
	private String valid; //是否有效（默认：Y），调用setValid()设置

	/**
	 * 插入之前执行方法，需要手动调用
	 */
	@Override
	public void preInsert() {
		// 不限制ID为UUID，调用setIsNewRecord()使用自定义ID
		if (!this.isNewRecord) {
			setId(IdGen.uuid());
		}

		Object obj = SecurityUtils.getSubject().getSession().getAttribute(EntityConstant.OPERATOR);

		/*if (obj instanceof SysAdmin) {
			SysAdmin sysAdmin = (SysAdmin) obj;
			this.createBy = sysAdmin.getId();
			this.updateBy = sysAdmin.getId();
		}*/

		if (this.createTime != null) {
			if (this.updateTime == null) {
				this.updateTime = this.createTime;
			}
		} else {
			this.updateTime = DateUtils.now();
			this.createTime = this.updateTime;
		}
	}

	/**
	 * 更新之前执行方法，需要手动调用
	 */
	@Override
	public void preUpdate() {
		Object obj = null;
		try {
			obj = SecurityUtils.getSubject().getSession().getAttribute(EntityConstant.OPERATOR);
		} catch (InvalidSessionException e) {
			LOGGER.debug("从shiro的session获取数据为空");
		}

		/*if (obj instanceof SysAdmin) {
			SysAdmin sysAdmin = (SysAdmin) obj;
			this.updateBy = sysAdmin.getId();
		}*/
		this.updateTime = DateUtils.now();
	}

	public Date getCreateTime() {
		return createTime;
	}

	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

	public Date getUpdateTime() {
		return updateTime;
	}

	public void setUpdateTime(Date updateTime) {
		this.updateTime = updateTime;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getCreateBy() {
		return createBy;
	}

	public void setCreateBy(String createBy) {
		this.createBy = createBy;
	}

	public String getUpdateBy() {
		return updateBy;
	}

	public void setUpdateBy(String updateBy) {
		this.updateBy = updateBy;
	}

	public String getValid() {
		if (StringUtils.isEmpty(valid)) {
			valid = "Y";
		}
		return valid;
	}

	public void setValid(String valid) {
		this.valid = valid;
	}
}
